package com.longjianghuasheng.logistics.ext

import androidx.lifecycle.MutableLiveData
import com.longjianghuasheng.logistics.data.model.bean.ApiResponseNoData
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.requestNoCheck
import me.hgj.jetpackmvvm.network.AppException
import me.hgj.jetpackmvvm.network.BaseResponse


//提交时的网络请求 直接回调给viewModel
fun <T> BaseViewModel.commit(
    block: suspend () -> BaseResponse<T>,
    success: (T) -> Unit, loadingMessage: String = "",
    error: (AppException) -> Unit = {
        toastNormal(it.errorMsg)

    },
    isToastSuccess: Boolean = false,
    isShowDialog: Boolean = true

) {
    requestNoCheck(block, {

        if (it.isSuccess()) {
            if (isToastSuccess) toastSuccess(it.getResponseMsg())
            success.invoke(it.getResponseData())
            return@requestNoCheck
        }


        error.invoke(
            AppException(
                it.getResponseCode(),
                it.getResponseMsg(),
                it.getResponseMsg()
            )
        )
    }, error, isShowDialog, loadingMessage)

//    request(block, success, error, true, loadingMessage)
}

//提交时的网络请求   交给view层接收
fun <T> BaseViewModel.commit(
    block: suspend () -> BaseResponse<T>,
    successLiveData: MutableLiveData<T>, loadingMessage: String = "",
    error: (AppException) -> Unit = {
        toastNormal(it.errorMsg)
    },
    isToastSuccess: Boolean = false,
    isShowDialog: Boolean = true
) {
    commit(block, {
        successLiveData.value = it
    }, loadingMessage, error, isToastSuccess, isShowDialog)
}


//提交时的网络请求   json里没有data时调用  在ViewModel层接收数据
fun <T : ApiResponseNoData> BaseViewModel.commit2(
    block: suspend () -> T,
    success: (T) -> Unit,
    loadingMessage: String = "",
    error: (AppException) -> Unit = {
        toastNormal(it.errorMsg)

    },
    isToastSuccess: Boolean = true,
    isShowDialog: Boolean = true
) {

    requestNoCheck(block, {

        if (it.isSuccess()) {
            if (isToastSuccess) toastNormal(
                it.getResponseMsg()
            )
            success.invoke(it)
            return@requestNoCheck
        }


        error.invoke(
            AppException(
                it.getResponseCode(),
                it.getResponseMsg(),
                it.getResponseMsg()
            )
        )
    }, error, isShowDialog, loadingMessage)

}


//提交时的网络请求  json里没有data时调用     交给view层接收
fun <T : ApiResponseNoData> BaseViewModel.commit2(
    block: suspend () -> T,
    successLiveData: MutableLiveData<T>, loadingMessage: String = "",
    error: (AppException) -> Unit = {
        toastNormal(it.errorMsg)
    },
    isToastSuccess: Boolean = true,
    isShowDialog: Boolean = true

) {
    commit2(block, {
        successLiveData.value = it
    }, loadingMessage, error, isToastSuccess, isShowDialog)

}

